package concurrencyPractice.chapter05;

import java.util.concurrent.CountDownLatch;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 程序5-11 在计时测试中使用 CountDownLatch 来启动和停止线程
 * @date 2024/1/2 14:31:19
 */
public class TestHarness {

    public long timeTasks(int nThreads, final Runnable task) throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);

        final CountDownLatch endGate = new CountDownLatch(nThreads);

        for (var i = 0; i <nThreads; i ++) {
            var t = new Thread() {
                public void run() {
                    try {
                        startGate.await();

                        try {
                            task.run();
                        } finally {
                            endGate.countDown();
                        }
                    } catch (InterruptedException ignored) {

                    }
                }
            };
            t.start();
        }
        long start = System.nanoTime();
        startGate.countDown();
        endGate.await();
        long end = System.nanoTime();
        return  end -start;
    }
}
